<template>
  <div>
    <!-- <div class="header">
      <a-space direction="vertical" style="width: 100%; padding: 10px 20px">
        <a-button type="primary" @click="handleEdit"> 新增账号 </a-button>
      </a-space>
    </div> -->
    <div class="b_table">
      <div style="display: flex; align-items: center; justify-content: space-between; height: 60px">
        <div> </div>
        <div style="position: relative; bottom: 10px">
          <a-button type="primary" @click="handleEdit"> 新增账号 </a-button>
        </div>
      </div>
      <a-table
        style="position: relative; bottom: 5px"
        ellipsis
        :loading="loading"
        bordered
        size="middle"
        class="ant-table-striped"
        :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
        :data-source="data.data"
        :columns="columns"
        stripe
        @change="Change"
      >
        <!-- headerCell个性化单元头,表的头 -->
        <template #headerCell="{ column }">
          <!-- 限制只有name才能是蓝色 -->
          <template v-if="column.key === 'user_id'">
            <span style="color: #1890ff">user_id</span>
          </template>
        </template>
        <!-- 搜索 -->
        <template
          #customFilterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
        >
          <div style="padding: 8px">
            <a-input
              ref="searchInput"
              :placeholder="`Search ${column.dataIndex}`"
              :value="selectedKeys[0]"
              style="display: block; width: 188px; margin-bottom: 8px"
              @change="(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])"
              @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
            />
            <a-button
              type="primary"
              size="small"
              style="width: 90px; margin-right: 8px"
              @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
            >
              <template #icon><SearchOutlined /></template>
              Search
            </a-button>
            <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
              Reset
            </a-button>
          </div>
        </template>
        <!-- 自定义筛选图标 -->
        <template #customFilterIcon="{ filtered }">
          <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }" />
        </template>
        <!-- 个性化单元格，数据 -->
        <template #bodyCell="{ text, column, record }">
          <template v-if="state.searchText && state.searchedColumn === column.dataIndex">
            <span>
              <template
                v-for="(fragment, i) in text
                  .toString()
                  .split(new RegExp(`(?<=${state.searchText})|(?=${state.searchText})`, 'i'))"
              >
                <mark
                  v-if="fragment.toLowerCase() === state.searchText.toLowerCase()"
                  :key="i"
                  class="highlight"
                >
                  {{ fragment }}
                </mark>
                <template v-else>{{ fragment }}</template>
              </template>
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'roles'">
            <div class="editable-row-operations">
              <a-tag color="#108ee9" v-for="(item, index) in text" :key="index">
                <span v-if="item == 'OTHER'">开发者</span>
                <span v-if="item == 'ADMIN'">超级管理</span>
                <span v-if="item == 'MEMBER'">普通用户</span>
                <span v-if="item == 'MERCHANT'">普通商家</span>
              </a-tag>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'status'">
            <div class="editable-row-operations">
              <a-tag color="#67C23A" v-if="record.status">
                <span>正常</span>
              </a-tag>
              <a-tag color="#F56C6C" v-else>
                <span>禁用</span>
              </a-tag>
            </div>
          </template>

          <template v-else-if="column.key === 'caozuo'">
            <div style="display: flex; justify-content: space-around">
              <el-icon @click="DataEdit(record)" color="#0960bd"><Edit /></el-icon>
              <el-icon @click="handleDelete(record.user_id)" color="red"><Delete /></el-icon>
            </div>
          </template>
        </template>
        <!-- 这个是二级table -->
        <!-- <template #expandedRowRender="{ record }">
          <p style="margin: 0">
            {{ record.nickName }}
          </p>
        </template> -->
      </a-table>
    </div>
    <!-- 用于注册 -->
    <BasicDrawer
      v-bind="$attrs"
      @register="register"
      @close="Close"
      title="详情"
      @ok="shot"
      :loading="DrawerData.loading"
      :isDetail="true"
      width="40%"
    >
      <RegisterUsers :rolesList="data.rolesList" @onReturn="registerReturn" />
    </BasicDrawer>

    <a-drawer
      title="管理员账号编辑"
      width="40%"
      :open="open"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      @close="onClose"
    >
      <UsersEdit
        @onReturn="onReturn"
        :select_title="select_title"
        :select_data="select_data"
        :roleList="data.rolesList"
      />
    </a-drawer>
  </div>
</template>
<script lang="ts" setup>
  import { SearchOutlined } from '@ant-design/icons-vue';
  import { reactive, ref, onMounted } from 'vue';
  import { Edit, Delete } from '@element-plus/icons-vue';
  import { adminStore } from '/@/store/locality/admin';
  import { authorityStore } from '/@/store/locality/authority';
  import { BasicDrawer, useDrawer } from '/@/components/Drawer';
  import RegisterUsers from './components/register.vue';
  import UsersEdit from './components/adminEdit.vue';
  import { message } from 'ant-design-vue';

  {
    RegisterUsers;
    UsersEdit;
  }
  const select_data = ref('');
  const select_title: any = ref('编辑');

  const open = ref(false);
  const loading = ref(true);
  const operation = adminStore();
  const AutStore = authorityStore();
  const DrawerData = ref({
    loading: false,
  });

  function registerReturn(item) {
    if (item == 'success') openDrawer(false, '');
  }
  function onReturn(item, type) {
    userEdit(item);
  }
  async function userEdit(item) {
    const d = await operation.AccoutUpdate(item);

    if (d.code == 200) {
      getData();
      open.value = false;
      message.success(d.message);
    } else {
      message.success(d.message);
    }
  }

  const onClose = () => {
    open.value = false;
  };

  const [register, { openDrawer, closeDrawer }] = useDrawer();
  // 获取角色列表
  async function getRolesList() {
    const result = await AutStore.GetRoleList({});

    var list1: any = [];
    result.data.filter((item) => {
      list1.push({
        label: item.name,
        value: item.id,
      });
    });
    data.value.rolesList = list1;
  }
  function Close(e) {
    closeDrawer();
  }
  function shot(record: Recordable) {
    // openDrawer(false, data);
    console.log(record);
  }
  async function handleDelete(user_id) {
    var data = {
      user_id: user_id,
    };
    const d = await operation.AccountDelete(data);

    if (d.code == 200) {
      getData();
      message.success('删除成功!');
    } else {
      message.error('删除失败!');
    }
  }
  async function getData() {
    const d = await operation.GetAdminList({
      pageNum: data.value.pageNum,
      pageSize: data.value.pageSize,
    });

    data.value.data = d.data;
    loading.value = false;
    data.value.loading = false;
    data.value.total = d.total;
  }

  const data = ref({
    data: [],
    loading: true,
    border: true,
    rolesList: [],
    total: 0,
    pageNum: 1,
    pageSize: 20,
  });

  const state = reactive({
    searchText: '',
    searchedColumn: '',
  });

  const DataEdit = (item) => {
    select_data.value = item;
    select_title.value = '编辑';
    open.value = true;
  };

  function handleEdit(record: Recordable) {
    openDrawer(true, record);
  }

  const searchInput = ref();
  // 数据规格
  const columns = [
    {
      title: '用户ID',
      dataIndex: 'user_id',
      key: 'user_id',

      // 开启搜索
      customFilterDropdown: true,
      // 搜索过滤
      onFilter: (value, record) =>
        record.user_id.toString().toLowerCase().includes(value.toLowerCase()),
      onFilterDropdownOpenChange: (visible) => {
        if (visible) {
          setTimeout(() => {
            searchInput.value.focus();
          }, 100);
        }
      },
    },
    {
      title: '用户账号',
      dataIndex: 'account',
      key: 'account',
    },

    {
      title: '用户昵称',
      dataIndex: 'nickName',
      key: 'nickName',
    },
    {
      title: '用户角色',
      dataIndex: 'roles',
      key: 'roles',

      // record.user_id.toString().toLowerCase().includes(value.toLowerCase()),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',

      // record.user_id.toString().toLowerCase().includes(value.toLowerCase()),
    },
    {
      title: '注册时间',
      dataIndex: 'register_date',
      key: 'register_date',
    },
    {
      title: '操作',
      dataIndex: 'user_id',
      key: 'caozuo',
      width: 100,
      fixed: 'right',
    },
  ];

  const handleSearch = (selectedKeys: any, confirm: any, dataIndex: any) => {
    confirm();
    state.searchText = selectedKeys[0];
    state.searchedColumn = dataIndex;
  };

  const Change = (pagination: any) => {
    console.log(pagination);
  };

  const handleReset = (clearFilters) => {
    clearFilters({ confirm: true });
    state.searchText = '';
  };

  onMounted(() => {
    getData();
    getRolesList();
  });
</script>
<style scoped>
  [data-doc-theme='light'] .ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
  }

  [data-doc-theme='dark'] .ant-table-striped :deep(.table-striped) td {
    background-color: rgb(29 29 29);
  }

  .highlight {
    padding: 0;
    background-color: rgb(255 192 105);
  }

  .b_table {
    margin: 20px;
    padding: 10px;

    /* margin: 20px; */
    background: white;
  }

  .header {
    width: 97%;
    height: 60px;
    margin: 20px;
    background-color: white;
  }
</style>
